package com.itfreer.ui.base.checkbox;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import com.itfreer.ui.R;
import com.itfreer.ui.base.api.IPower;
import com.itfreer.ui.base.api.ISimpleView;

/**
 * 自定义CheckBox，解决数据绑定问题
 */
public class CheckBox extends android.support.v7.widget.AppCompatCheckBox implements ISimpleView, IPower {

    private String fieldName;
    private Object fieldValue;
    private String securityID;
    private boolean securityVisible=true;

    public CheckBox(Context context) {
        super(context);
    }

    public CheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
        getAttrs(context, attrs);
    }

    public CheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        getAttrs(context, attrs);
    }

    protected void getAttrs(Context context, AttributeSet attrs){
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SimpleView);
        fieldName = a.getString(R.styleable.SimpleView_fieldName);
        securityID = a.getString(R.styleable.SimpleView_securityID);
    }

    /**
     * 设置绑定的依据对象
     * @param name
     */
    @Override
    public void setFieldName(String name){
        this.fieldName = name;
    }

    /**
     * 获取绑定的依据对象
     * @return
     */
    @Override
    public String getFieldName(){
        return fieldName;
    }

    /**
     * 设置绑定的值
     * @param value
     */
    @Override
    public void setFieldValue(Object value){
        this.fieldValue = value;
        if(fieldValue!=null && (boolean)fieldValue){
            this.setChecked(true);
        }else{
            this.setChecked(false);
        }
    }

    /**
     * 获取当前的值
     * @return
     */
    @Override
    public Object getFieldValue(){
        fieldValue = this.isChecked();
        return fieldValue;
    }

    /**
     * 获取权限ID
     * @return
     */
    public String getSecurityID(){
        return securityID;
    }

    /**
     * 没有权限时，设置是否可见
     * @param visible
     */
    public void setSecurityVisible(boolean visible){
        securityVisible = visible;
        if(visible){
            this.setVisibility(View.VISIBLE);
        }else{
            // 表示不可见并且不占用空间
            this.setVisibility(View.GONE);
        }
    }
}
